package com.guangfeng.yql.comm.netty.initalizer;

import cn.hutool.extra.spring.SpringUtil;
import com.guangfeng.yql.comm.netty.NettyProperty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.stereotype.Component;

/**
 * 图片传输 netty 初始化通道
 */
@Component
public class ImageInitializer extends BaseInitializer<SocketChannel> {

    private EventExecutorGroup businessEventExecutorGroup = new DefaultEventExecutorGroup(10);

    @Override
    public void init(NettyProperty nettyProperty) {
        setNettyProperty(nettyProperty);
    }


    /**
     * This method will be called once the {@link Channel} was registered. After the method returns this instance
     * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
     *
     * @param ch the {@link Channel} which was registered.
     * @throws Exception is thrown if an error occurs. In that case it will be handled by
     *                   which will by default close
     *                   the {@link Channel}.
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast("httpServerCodec", new HttpServerCodec());
        // 请求解码
        pipeline.addLast("httpRequestDecoder", new HttpRequestDecoder());
        // 响应编码
        pipeline.addLast("httpResponseEncoder", new HttpResponseEncoder());
        //  相应合并
        pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(getNettyProperty().getMaxContentLength()));
        pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler(getNettyProperty().getPath(), null, true, getNettyProperty().getMaxFrameSize()));
        // 添加自定义事件处理
        pipeline.addLast(getNettyProperty().getHandler().getName(), SpringUtil.getBean(getNettyProperty().getHandler()));

    }
}
